package com.chang.bootplus.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.entity.*;
import com.chang.bootplus.po.*;
import com.chang.bootplus.service.*;
import com.chang.bootplus.vo.SchoolAdminVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = {"用户管理"})
@RestController
public class AdminUserController {

    @Autowired
    SchoolService schoolService;


    @Autowired
    StudentService studentService;

    @Autowired
    StuTestService stuTestService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleService roleService;


    @PostMapping("/user/info")
    @ApiOperation(httpMethod = "POST", value = "用户详情")
    public ApiResponse<SchoolAdminVO> info(@RequestBody SchoolIdPO po) {
        School byId = schoolService.getById(po.getId());
        Assert.notNull(byId, "找不到该用户");
        SchoolAdminVO schoolAdminVO = BeanUtil.beanA2beanB(byId, SchoolAdminVO.class);
        List<Role> roles = roleService.listRolesByUserId(po.getId());
        schoolAdminVO.setRoleList(roles);
        return new ApiResponse(schoolAdminVO);
    }

    @ApiOperation(httpMethod = "POST", value = "用户列表")
    @PostMapping("/user/list")
    public ApiResponse<SchoolAdminVO> list(@RequestBody SchoolAdminPO po) {
        Page<School> schoolPage = new Page<>(po.getPageNumber(),po.getPageSize());
        int count = schoolService.count();
        long total = schoolPage.getTotal();
        if (po.getUsername()==null){
            schoolPage = schoolService.page(schoolPage, new LambdaQueryWrapper<School>());
        }else {
            schoolPage = schoolService.page(schoolPage, new LambdaQueryWrapper<School>().like(StrUtil.isBlank(po.getUsername()), School::getNickName, po.getUsername()));
        }
        List<SchoolAdminVO> schoolAdminVOS = BeanUtil.listA2ListB(schoolPage.getRecords(), SchoolAdminVO.class);
        return new ApiResponse(schoolAdminVOS,schoolPage.getTotal(),new Long(count));
    }

    @PostMapping("/user/save")
    @ApiOperation(httpMethod = "POST", value = "添加用户")
    public ApiResponse<Void> save( @RequestBody SchoolAddPO sysUser) {
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getSchoolName, sysUser.getSchoolName()));
        if (one!=null){
            throw new BusException("该学校已注册");
        }
        School school = BeanUtil.beanA2beanB(sysUser, School.class);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 默认密码
        String password = encoder.encode("123456");
        school.setPassword(password);
        schoolService.save(school);
        return new ApiResponse("添加成功");
    }

    @PostMapping("/user/update")
    @ApiOperation(httpMethod = "POST", value = "更新用户")
    public ApiResponse<Void> update( @RequestBody SchoolUpdatePO sysUser) {
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getSchoolName, sysUser.getSchoolName()));
        School school = BeanUtil.beanA2beanB(sysUser, School.class);
        school.setId(one.getId());
        schoolService.updateById(school);
        return new ApiResponse("更新成功");
    }

    @Transactional
    @PostMapping("/user/delete")
    @ApiOperation(httpMethod = "POST", value = "删除用户")
    public ApiResponse<Void> delete(@RequestBody UserPOIds po) {
        List<Long> longs = Arrays.asList(po.getIds());// 学校id
        List<School> schools = schoolService.listByIds(longs);
        List<String> stuIds=new LinkedList<>();
        List<Student> list=new LinkedList<>();
        for (School s:schools){
            list=studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getSchoolName, s.getSchoolName()));
            stuIds = list.stream().map(t1 -> t1.getStuId()).collect(Collectors.toList());
        }
        // 删除学生成绩
        stuIds.stream().forEach(t->{
            stuTestService.remove(new LambdaQueryWrapper<StuTest>().eq(StuTest::getSchoolName,schools.get(0).getSchoolName()).eq(StuTest::getStuId,t));
        });
        List<Long> collect = list.stream().map(t -> t.getId()).collect(Collectors.toList());
        studentService.removeByIds(collect);// 删除学生ids
        schoolService.removeByIds(longs);

        userRoleService.remove(new QueryWrapper<UserRole>().in("user_id", po.getIds()));

        return new ApiResponse("删除成功");
    }

    @Transactional
    @PostMapping("/role/prem")
    @ApiOperation(httpMethod = "POST", value = "给用户授权")
    public ApiResponse<Void> rolePerm(@RequestBody UserPO po) {

        List<UserRole> userRoles = new ArrayList<>();

        Arrays.stream(po.getRoleIds()).forEach(r -> {
            UserRole sysUserRole = new UserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(po.getUserId());
            userRoles.add(sysUserRole);
        });

        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", po.getUserId()));
        userRoleService.saveBatch(userRoles);

        // 删除缓存
        School sysUser = schoolService.getById(po.getUserId());
        schoolService.clearUserAuthorityInfo(sysUser.getSchoolName());
        return new ApiResponse("授权成功");
    }

    @PostMapping("/user/repass")
    @ApiOperation(httpMethod = "POST", value = "重置密码")
    public ApiResponse<Void> repass(@RequestBody SchoolIdPO po) {
        School sysUser = schoolService.getById(po.getId());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        sysUser.setPassword(encoder.encode("123456"));
        schoolService.updateById(sysUser);
        return new ApiResponse("重置成功");
    }

    @PostMapping("/user/updaterepass")
    @ApiOperation(httpMethod = "POST", value = "修改密码")
    public ApiResponse<Void> updaterepass(@RequestBody SchoolPassPO po) {
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, po.getNickname()));
        BCryptPasswordEncoder encoder1 = new BCryptPasswordEncoder();
        one.setPassword(encoder1.encode(po.getPassword()));
        schoolService.updateById(one);
        return new ApiResponse("修改成功");
    }

}
